package com.jzo2o.market.handler;

import com.jzo2o.market.enums.ActivityStatusEnum;
import com.jzo2o.market.enums.CouponStatusEnum;
import com.jzo2o.market.mapper.ActivityMapper;
import com.jzo2o.market.mapper.CouponMapper;
import com.jzo2o.market.model.domain.Activity;
import com.jzo2o.redis.sync.SyncManager;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.function.Consumer;

@Component
public class XxlJobHandler {

    @Resource
    private SyncManager syncManager;

    @Resource
    private ActivityMapper activityMapper;

    @Resource
    private CouponMapper couponMapper;

    /**
     * 活动状态修改，
     * 1.活动进行中状态修改
     * 2.活动已失效状态修改
     * 1分钟一次
     */
    @XxlJob("updateActivityStatus")
    public void updateActivitySatus(){
        List<Activity> select = activityMapper.select();
        select.stream().forEach(new Consumer<Activity>() {
            @Override
            public void accept(Activity activity) {
                // 活动进行中状态修改
                if(activity.getDistributeStartTime().isBefore(LocalDateTime.now())
                        && activity.getDistributeEndTime().isAfter(LocalDateTime.now())){
                    activity.setStatus(ActivityStatusEnum.DISTRIBUTING.getStatus());
                    activityMapper.updateById(activity);
                }
                if(activity.getDistributeEndTime().isBefore(LocalDateTime.now())){
                    activity.setStatus(ActivityStatusEnum.LOSE_EFFICACY.getStatus());
                    activityMapper.updateById(activity);
                }
            }
        });
    }

    /**
     * 已领取优惠券自动过期任务
     */
    @XxlJob("processExpireCoupon")
    public void processExpireCoupon() {
        couponMapper.updateByNow(CouponStatusEnum.INVALID.getStatus(),LocalDateTime.now());
    }


}
